package com.zretc.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.entity.Comment;
import com.zretc.entity.Product;
import com.zretc.entity.User;
import com.zretc.service.CommentService;
import com.zretc.service.impl.CommentServiceImpl;

/**
 * Servlet implementation class FrontCommentServlet
 */
@WebServlet("/front/comment")
public class FrontCommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private CommentService commentService = new CommentServiceImpl();
       
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取商品编号
		Integer productId = Integer.valueOf(request.getParameter("productId"));
		
		// 获取商品评论
		List<Comment> list = commentService.commentListByProductId(productId);
		
		// list集合转换为json字符串
		String json = new Gson().toJson(list);
		
		// 响应输出
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 评论内容
		String commentContent = request.getParameter("commentContent");
		// 用户id
		User user = new User();
		Integer userId = Integer.valueOf(request.getParameter("userId"));
		user.setUserId(userId);
		// 商品id
		Product product = new Product();
		Integer productId = Integer.valueOf(request.getParameter("productId"));
		product.setProductId(productId);
		// 评论时间
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date = new Date();
		String commentTime = format.format(date);
		// 父类编号
		Integer commentFatherId = Integer.valueOf(request.getParameter("commentFatherId"));
		// 无评分
		Integer commentScore = 0;
		String commentScoreParam = request.getParameter("commentScore");
		if(commentScoreParam!=null) {
			commentScore = Integer.valueOf(commentScoreParam);
		}
		Comment comment = new Comment(null, user, product, commentTime, commentContent, commentFatherId, commentScore);
		
		// 插入数据库
		commentService.insertComment(comment);
		
		
	}

}
